// pages/songdetail/songdetail.js
import request from '../../utils/request'
//获取全局实例
const appinstance = getApp();
Page({

  /**
   * 页面的初始数据
   */
  data: {
    isplay: false, //是否播放
    musicdetail: '', //歌曲详情信息
    musicurl: '', //音乐链接
    index: 0, //音乐索引
    musicid:'',//音樂id
    displayMusicList: [], //音乐列表
    realtime: '00:00', //实时时间
    totalduration: '00:00', //总时长
    currtimer: 0, //进度条长度
    playtype: 'random', //播放类型 single  order
    animationstate: false, //动画加载
    showList: 73, //音乐列表移动距离
    handshowlyric: false, //歌词的显示
    lyric: [], //歌词
    activeindex: 0, //标记歌词高亮索引
    updistance: 0, //歌词滚动距离
    isLike:false,//是否喜歡當前歌曲
    likemusiclist:[],//喜欢音乐列表

  },

  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function(options) {
    // console.log(options)
    // this.setData({
    //   isplay: appinstance.musicdata.musicisplay
    // })


    // this.geteventChanneldata();
    // 通过getOpenerEventChannel对象,对`parentPageEmit`进行监听
    // const eventChannel = this.getOpenerEventChannel();
    // eventChannel.on('parentPageEmit',(data) => {
    //   // console.log(data.data);
    //   this.setData({
    //     index:data.data
    //   })
    // });

    let displayMusicList = wx.getStorageSync('playingMusicList')
    console.log(displayMusicList);
    this.setData({
      displayMusicList
    })


    //如果有歌曲id
    if (options.songid) {
      this.setData({
        musicid: options.songid
      })
      this.getdetailmusic(options.songid)
      this.getPlayingMusicIndex(options.songid)

    }




    //解决音频与页面的播放不一致问题
    //获取音乐实例  监听音乐的播放、暂停、停止
    this.BackgroundAudioManager = wx.getBackgroundAudioManager();
    this.BackgroundAudioManager.onPlay(() => {


      appinstance.musicdata.musicid = options.songid

      this.changeplay(true)
    });
    this.BackgroundAudioManager.onPause(() => {
      this.changeplay(false)
    });
    this.BackgroundAudioManager.onStop(() => {
      this.changeplay(false)
    });

    //监听背景音频自然播放结束事件
    this.BackgroundAudioManager.onEnded(() => {
      //切换下一曲
      this.handmusicplayend(this.data.playtype);
      //修改实时播放时长
      this.setData({
        currtimer: 0,
        realtime: '00:00'
      })
    })

    //获取实时播放时间
    this.BackgroundAudioManager.onTimeUpdate(() => {
      //实时时间
      let realtime = this.gettimer(this.BackgroundAudioManager.currentTime * 1000)
      // console.log(realtime)
      //百分百比
      let currtimer = (this.BackgroundAudioManager.currentTime / this.BackgroundAudioManager.duration).toFixed(2) * 100
      //console.log(currtimer)
      // console.log(this.BackgroundAudioManager.currentTime+"aaaaaaaa11111111")
      this.setData({
        realtime,
        currtimer
      })

      //监听歌词的高亮
      this.changelyric();
    })

    //获取用户喜欢音乐
    this.getIsLike();


  },
  // 获取当前播放歌曲在歌单中的索引
  getPlayingMusicIndex(musicId) {
    let {
      index,
      displayMusicList
    } = this.data
    index = displayMusicList.findIndex(item => {
      return item.id == musicId
    })
    this.setData({
      index
    })
  appinstance.musicdata.musicindex = index
  },
  //音乐详情
  getdetailmusic(musicid) {
    let musicdetail = '';
    let totalduration = '';
    request('/song/detail', {
        ids: musicid
      })
      .then(res => {
        console.log(res)
        musicdetail = res;
        totalduration = this.gettimer(res.songs[0].dt);
        // totalduration =res.songs[0].dt
        this.setData({
          musicdetail,
          totalduration
        })

        //判断播放
        // if (appinstance.musicdata.musicisplay==false && appinstance.musicdata.musicid == musicid) {
        //   this.setData({
        //     isplay: true
        //   })

        // } else {
        //   this.hideispaly()
        // }
        if (appinstance.musicdata.musicid == musicid && appinstance.musicdata.musicisplay == true) {
          this.setData({
            isplay: true
          })
        } else {
          this.hideispaly()
          //获取歌词
          this.getlyric()
        }

      })
  },
  //修改时间格式 毫秒
  gettimer(timer) {

    let s = parseInt((timer / 1000) % 60)
    let m = parseInt((timer / 1000) / 60)
    if (m < 10) {
      m = '0' + m
    }
    if (s < 10) {
      s = '0' + s
    }
    // m<10?'0'+m:m;
    // s<10?'0'+s:s;
    timer = m + ':' + s
    // console.log('m' + m)
    // console.log('s' + s)
    // console.log('timer'+timer)
    return timer
  },
  //接收父级传过来的数据
  // geteventChanneldata(){
  //   // 通过getOpenerEventChannel对象,对`parentPageEmit`进行监听
  //   const eventChannel = this.getOpenerEventChannel();
  //   eventChannel.on('parentPageEmit', (data) => {
  //     console.log(data);

  //   });
  // },
  //修改播放状态
  changeplay(isplay) {
    this.setData({
      isplay
    })
    appinstance.musicdata.musicisplay = isplay;
  },
  //slider的拖拽
  touchmove1(event) {
    this.BackgroundAudioManager.pause();
    console.log(event.detail.value)
    let currtimer = event.detail.value
    //音频跳转的位置，单位 s
    this.BackgroundAudioManager.seek(currtimer / 100 * this.BackgroundAudioManager.duration)
    console.log(this.BackgroundAudioManager.duration)
    //实时时间
    let realtime = this.gettimer(currtimer / 100 * this.BackgroundAudioManager.duration * 1000)
    console.log(realtime)
    this.setData({
      currtimer,
      realtime
    })

    this.BackgroundAudioManager.play();

  },
  //拖拽
  //   touchmove(event){
  //     //var px = rpx / 750 * wx.getSystemInfoSync().windowWidth;
  //     //var rpx = px * 750 / wx.getSystemInfoSync().windowWidth;

  //     //可使用窗口宽度，单位px
  //     let windowWidth = wx.getSystemInfoSync().windowWidth

  //     //除去进度条,text宽度,即拖拽点前面的多余的宽度
  //     let distancex = (750-610)/2
  //     //拖拽的距离 rpx
  //     let handdistancex = event.touches["0"].clientX * 750 / wx.getSystemInfoSync().windowWidth - distancex - 80
  //     //百分百比
  // //  console.log(handdistancex)

  //     let currtimer =   (handdistancex/450).toFixed(2)*100

  //     // this.BackgroundAudioManager.currentTime = currtimer*this.BackgroundAudioManager.duration 
  //    //音频跳转的位置，单位 s
  //     this.BackgroundAudioManager.seek(currtimer/100 * this.BackgroundAudioManager.duration)
  //  //   console.log(currtimer/100 * this.BackgroundAudioManager.duration)
  //     //实时时间
  //     let realtime = this.gettimer(currtimer/100 * this.BackgroundAudioManager.duration)


  //     this.setData({
  //        currtimer,
  //       realtime
  //        })

  //   },
  // handclick(event){
  //    //var px = rpx / 750 * wx.getSystemInfoSync().windowWidth;
  //   //var rpx = px * 750 / wx.getSystemInfoSync().windowWidth;
  //   //点击的位置,px=>rpx
  //   let clientx = event.touches["0"].clientX * 750 / wx.getSystemInfoSync().windowWidth
  //   //除去进度条,text宽度,即点击位置前面的多余的宽度
  //   let distancex = (750 - 610) / 2
  //   //点击位置到进度条左边的距离 rpx
  //   let handdistancex = clientx - distancex - 80

  //   //百分百比
  //   let currtimer = (handdistancex / 450).toFixed(2) * 100
  //   //音频跳转的位置，单位 s
  //   this.BackgroundAudioManager.seek(currtimer / 100 * this.BackgroundAudioManager.duration)
  // //  console.log(currtimer / 100 * this.BackgroundAudioManager.duration)
  //   //实时时间
  //   let realtime = this.gettimer(currtimer / 100 * this.BackgroundAudioManager.duration)


  //   this.setData({
  //     currtimer,
  //     realtime
  //   })

  // },

  //播放暂停
  hideispaly() {
    this.setData({
      isplay: !this.data.isplay,
      //动画
      animationstate: true,
    })
    // this.getAudioplay(this.data.musicdetail.songs[0].al.id, this.data.isplay, this.data.musicurl)
    this.getAudioplay(this.data.musicid, this.data.isplay, this.data.musicurl)
  },
  //wx.getBackgroundAudioManager 获取播放实例
  getAudioplay(songid, isplay, musicurl) {

    if (isplay) {
      if (!musicurl) {
        //获取歌曲url
        request('/song/url', {
            id: this.data.musicdetail.privileges[0].id
          })
          .then(res => {
            console.log(res)

            //获取音频实例
            this.BackgroundAudioManager.src = res.data[0].url;
            this.BackgroundAudioManager.title = this.data.musicdetail.songs[0].al.name;
            // console.log(this.BackgroundAudioManager.src)
            //将音乐链接存储，减少请次数
            musicurl = res.data[0].url
            this.setData({
              musicurl
            })

          })
      }
      // else{
      //   //获取音频实例
      //   this.BackgroundAudioManager.src = musicurl;
      //   this.BackgroundAudioManager.title = this.data.musicdetail.songs[0].al.name;


      // }

      this.BackgroundAudioManager.play();
    } else {
      this.BackgroundAudioManager.pause();

    }
  },
  //切换歌曲
  // handmusicplay(event){
  //   this.setData({
  //     animationstate:false,
  //   })
  //   let type = event.currentTarget.dataset.type
  //   let {displayMusicList,index} = this.data

  //   if(type == 'next'){
  //     if (index < displayMusicList.length){
  //       index++
  //     }else{
  //       index = 0
  //     }

  //   }else{
  //     if (index > 0) {
  //       index--
  //     } else {
  //       index = displayMusicList.length-1
  //     }
  //   }
  //   this.setData({
  //     index,
  //     musicurl:'',
  //     animationstate:true,
  //   })
  //  let musicid = displayMusicList[index].id
  //   // console.log(musicid)
  //   // console.log(index)
  //   this.getdetailmusic(musicid)
  //   this.hideispaly()

  // },
  //切换歌曲
  handmusicplay(event) {
    this.setData({
      animationstate: false,
    })
    let type = event.currentTarget.dataset.type

    let {
      displayMusicList,
      index,
      playtype
    } = this.data

    if (playtype == 'random') {
      index = Math.round(Math.random() * (displayMusicList.length - 1));
    } else {

      if (type == 'next') {
        if (index < displayMusicList.length) {
          index++
        } else {
          index = 0
        }

      } else {
        if (index > 0) {
          index--
        } else {
          index = displayMusicList.length - 1
        }
      }

    }

    this.setData({
      index,
      musicurl:'',
      animationstate: true,
      isplay: false
    })
    appinstance.musicdata.musicindex = index;
    //当前音乐id
    let musicid = displayMusicList[index].id
    this.setData({
      musicid
    })
    this.getdetailmusic(musicid)

    //判断用户是否喜欢当前歌曲
    this.getIsLike();


  },
  //播放结束
  handmusicplayend(types) {
    this.setData({
      animationstate: false,
    })
    let type = types
    let {
      displayMusicList,
      index
    } = this.data
    switch (type) {
      case 'random':
        console.log('random')
        index = Math.round(Math.random() * (displayMusicList.length - 1));
        break;
      case 'single':

        index = index;
        console.log('single', index)

        break;
      case 'order':
        console.log('order')
        if (index < displayMusicList.length) {
          index++
        } else {
          index = 0;
        }
        break;
    }


    this.setData({
      index,
      musicurl: '',
      animationstate: true,
    })
    let musicid = displayMusicList[index].id
    // console.log(musicid)
    // console.log(index)
    this.getdetailmusic(musicid)
    this.hideispaly()

  },
  //修改播放单曲，循环，随机
  handplaytype() {
    let playtype = this.data.playtype;
    switch (playtype) {
      case 'random':
        playtype = 'single'
        break;
      case 'single':
        playtype = 'order'
        break;
      case 'order':
        playtype = 'random'
        break;
    }
    this.setData({
      playtype
    })
  },

  // 显示歌单列表
  showMusicList() {
    this.setData({
      showList: 0
    })
  },

  // 点击遮罩层 隐藏歌单列表
  hideMusicList() {
    this.setData({
      showList: 73
    })
  },
  //音乐列表点击播放歌曲
  handplaymusic(event) {
    let {
      index,
      musicid
    } = event.currentTarget.dataset
    if (this.data.musicid != musicid.toString()) {

      //将number转化为string
      this.data.musicid = musicid.toString()
      this.setData({
        musicdetail: '', //歌曲详情信息
        musicurl: '', //音乐链接
        isplay: false,
        index,
        musicid
      })
      //更新app全局播放列表当前index
      appinstance.musicdata.musicindex = index;

      this.getdetailmusic(this.data.musicid)

      //获取用户喜欢音乐
      this.getIsLike();

    } else {
      this.setData({
        isplay: !this.data.isplay
      })
      this.hideispaly()

    }


  },
  //切换歌词的显示隐藏,获取歌词
  handshowlyr() {

    this.setData({
      handshowlyric: !this.data.handshowlyric
    })
    if (this.data.handshowlyric == true && this.data.lyric.length <= 1) {
      //获取歌词
      this.getlyric()
    }

  },
  //获取歌词
  getlyric() {
    this.setData({
      lyric: [],
    })
    request('/lyric', {
        id: this.data.musicdetail.songs[0].id
      })
      .then(res => {

        //  console.log(res.lrc.lyric)
        let obj = res.lrc.lyric.split('[').slice(1).map(item => {
          let arr = item.trim().split(']');

          return {
            time: arr[0].slice(0, 5),
            text: arr[1]
          }
        })
        // console.log(obj)
        this.setData({
          lyric: obj
        })


      })
  },
  //监听歌词的高亮
  changelyric() {
    // activeindex  realtime
    let {
      activeindex,
      realtime,
      lyric,
      updistance
    } = this.data;

    for (let i = 0; i < lyric.length; i++) {
      if (lyric[i].time === realtime) {
        if (activeindex !== i) {
          updistance = 35 * i
          this.setData({
            activeindex: i,
            updistance
          })


          break;
        }
      }
    }
  },

  // 喜欢或取消喜欢该音乐
  async like() {
    let {musicid , likemusiclist} = this.data
    this.setData({
      isLike: !this.data.isLike
    })
    // 是否喜欢该音乐
   await request('/like', {
     id: musicid,
      like: this.data.isLike
    })
    // 修改likemusiclist 从喜欢列表中添加或删除当前id
    if (this.data.isLike) {
      likemusiclist.push(musicid)
    } else {
      let index = likemusiclist.findIndex(item => {
        return item == musicid
      })
      likemusiclist.splice(index, 1)
    }
    // 存入全局变量
    appinstance.musicdata.likemusiclist = likemusiclist
  },



  // 判断登录用户是否喜欢该音乐
  async getIsLike() {
    let { musicid, likemusiclist} = this.data
    if (wx.getStorageSync('userId')) {
      console.log(wx.getStorageSync('userId'));
      if (appinstance.musicdata.likemusiclist.length == 0) {
        await this.getLikeList()
      }
      likemusiclist = appinstance.musicdata.likemusiclist;
      // console.log(likeList);
      let flag = likemusiclist.find(item => {
        // console.log(item);
        return item == musicid
      })
      // 如果用相同的id，find返回该id值
      // console.log(flag)
      if (flag == undefined) {
        this.setData({
          isLike: false,
        })
      } else {
        this.setData({
          isLike: true
        })
      }
    }
  },
//获取喜欢音乐类表
  async getLikeList() {
    let userId = wx.getStorageSync('userId')
    let result = await request('/likelist', { uid: userId })
      console.log(result);
    // 存入全局变量
        appinstance.musicdata.likemusiclist = result.ids;
 
    // console.log('执行了getlikelist');
  },

  // 跳转如评论页面
  toComments() {
   
    let {musicid} = this.data
    console.log(musicid)
    wx.navigateTo({
      url: '/pages/comment/comment?musicid=' + musicid
    })
  },

  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady: function() {

  },

  /**
   * 生命周期函数--监听页面显示
   */
  onShow: function() {

  },

  /**
   * 生命周期函数--监听页面隐藏
   */
  onHide: function() {

  },

  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload: function() {

  },

  /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
  onPullDownRefresh: function() {

  },

  /**
   * 页面上拉触底事件的处理函数
   */
  onReachBottom: function() {

  },

  /**
   * 用户点击右上角分享
   */
  onShareAppMessage: function() {

  }
})